package org.example.springai_deepseek.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

/**
 * @author 沐雨栉风
 * @version 1.0
 * @description
 * @date 2025/2/28 18:33
 */
@RestController
@CrossOrigin("*")
@Slf4j
public class DeepSeekController {

    private final ChatClient chatClient;
    private final InMemoryChatMemory inMemoryChatMemory;

     //构造方法，用于构造chatclient 实例
    public DeepSeekController(ChatClient.Builder chatClientBuilder, InMemoryChatMemory inMemoryChatMemory) {
        this.inMemoryChatMemory = inMemoryChatMemory;
        // 设定系统提示词
        chatClientBuilder.defaultSystem("你是一个智能机器人,你的名字叫 Spring AI智能机器人");
        this.chatClient = chatClientBuilder.build();
    }


    @GetMapping("/chat")
    public String chat(@RequestParam(value = "message") String message) {
        return chatClient.prompt(message).call().content();
    }


    @RequestMapping(value = "stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> streamChat(@RequestBody ChatRequest request) {
        return chatClient.prompt(request.message)
                .stream().content().map(content -> ServerSentEvent.builder(content).event("message").build())
                //问题回答结速标识,以便前端消息展示处理
                .concatWithValues(ServerSentEvent.builder("[DONE]").build())
                .onErrorResume(e -> Flux.just(ServerSentEvent.builder("Error: " + e.getMessage()).event("error").build()));
    }

    /**
     * 开启记忆的聊天
     * @param request
     * @return
     */
    @PostMapping(value = "streamMemory", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> streamChatMemory(@RequestBody ChatRequest request) {
        //用户id
        String userId = request.userId();

        return chatClient.prompt(request.message())
                .advisors(new MessageChatMemoryAdvisor(inMemoryChatMemory, userId, 10), new SimpleLoggerAdvisor())
                .stream().content().map(content -> ServerSentEvent.builder(content).event("message").build())
                //问题回答结速标识,以便前端消息展示处理
                .concatWithValues(ServerSentEvent.builder("[DONE]").build())
                .onErrorResume(e -> Flux.just(ServerSentEvent.builder("Error: " + e.getMessage()).event("error").build()));
    }


    /**
     * 请求体
     * @param userId    用户ID，用于记忆对话内容
     * @param message   具体消息
     */
    record ChatRequest(String userId, String message) {

    }



}
